<template>
  <v-md-editor
    v-model="text"
    :disabled-menus="[]"
    :left-toolbar="leftToolbar"
    :toolbar="toolbar"
    height="100vh"
    @save="onSaveClicked"
    @upload-image="handleUploadImage"
  ></v-md-editor>
</template>

<script setup>
import { defineProps, onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { apiGetArticleDetail, apiPostImage, apiPutArticleContent } from '@/http/article'

const props = defineProps({
  id: String
})

const router = useRouter()

const pageData = reactive({
  content: '', // 文章内容
  tag_id: 1, // 文章标签ID
  title: '', // 文章标题
  tag_name: '',
  summary: '', // 文章摘要,
  id: null // 文章ID,
})
const { id } = toRefs(props)
const articleID = ref(id.value)
const text = ref('')
const leftToolbar =
  'undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | save | customToolbar'
const toolbar = {
  customToolbar: {
    title: '工具栏菜单',
    icon: 'v-md-icon-preview',
    menus: [
      {
        name: 'menu1',
        text: '查看',
        action() {
          router.push(`/article/${id.value}`)
        }
      },
      {
        name: 'menu2',
        text: '管理',
        action() {
          router.push('/manage')
        }
      }
    ]
  }
}

const initData = async () => {
  await apiGetArticleDetail(articleID.value).then((res) => {
    pageData.content = res.data.content
    pageData.tag_id = res.data.tag_id
    pageData.tag_name = res.data.tag
    pageData.id = res.data.id
    text.value = pageData.content
    document.title = `编辑:${res.data.title}`
  })
}

onMounted(() => {
  initData(false)
})

function handleUploadImage(event, insertImage, files) {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  apiPostImage(files[0], pageData.id).then((res) => {
    window.notyf.success('图片上传成功')
    insertImage({
      url: res.data.url,
      desc: ''
    })
  })
}

function onSaveClicked(textValue, html) {
  apiPutArticleContent(id.value, textValue).then(() => {
    window.notyf.success('保存成功')
  })
}
</script>

<style>
.n-drawer-header__main {
  width: 100%;
}
</style>
